<template>
  <div class="user-login">
    <h1>登录</h1>
    <form @submit.prevent="loginUser">
      <div class="form-group">
        <label for="email">邮箱</label>
        <input type="email" id="email" v-model="email" required />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <button type="submit">登录</button>
    </form>
    <p>还没有账户？<router-link to="/register">注册</router-link></p>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { loginUser as apiLoginUser } from '../services/api'; // 引入 API 服务
import { useUserStore } from '../stores/userStore'; // 引入 Pinia store

const email = ref('');
const password = ref('');
const router = useRouter(); // 获取路由实例
const store = useUserStore(); // 获取 Pinia store

const loginUser = async () => {
  const userData = {
    email: email.value,
    password: password.value,
  };

  try {
    const response = await apiLoginUser(userData); // 调用 API 服务
    console.log('登录成功:', response.data);

    // 存储 token 到 localStorage
    localStorage.setItem('token', response.data.token);
    
    // 更新登录状态
    store.setLoggedIn(true); // 更新 Pinia store 中的登录状态

    // 跳转到用户个人资料或首页
    router.push('/profile');
  } catch (error) {
    ElMessage.error('登录失败，请检查您的邮箱和密码');
  }
};
</script>

<style scoped>
.user-login {
  max-width: 400px;
  margin: 100px auto;
  padding: 20px;
  background: transparent;
  color: #f3f4f6;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background: #111827;
  color: #f3f4f6;
  transition: border-color 0.3s;
}

input:focus {
  border-color: #3450ff;
  outline: none;
}

button {
  width: 100%;
  padding: 10px;
  background: #3450ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

button:hover {
  background: #2440db;
}

p {
  text-align: center;
  margin-top: 15px;
}
</style>
